<template>
	<div id="friend-merchant-manage" class="w-h-100 pos-r flex-1 apply-container" style="box-sizing: border-box; overflow: hidden">
		<div class="w-h-100 ver-flex pos-a" style="box-sizing: border-box; padding: 6px">
			<div class="search-s page-public-s" style="box-sizing: border-box">
				<el-card shadow="never" :body-style="{ paddingBottom: '0' }">
					<el-form class="box-f" ref="queryForm" :inline="true">
						<!-- <el-form-item label="岗位名称：">
                            <el-input v-model="transferVal2" placeholder="请输入岗位名称" />
                        </el-form-item> -->
						<el-form-item>
							<el-button v-if="$hasPer('quarterlyAssessmentProdSafetyResponsibility1:add')" @click="addNodeClick" icon="ele-Plus" type="primary"> 新增 </el-button>
						</el-form-item>
					</el-form>
				</el-card>
			</div>

			<div style="box-sizing: border-box" class="flex-1 pos-r">
				<div class="pos-a w-h-100" style="box-sizing: border-box">
					<el-card class="box-card w-h-100" shadow="never" style="margin-top: 16px">
						<div style="" class="w-h-100 ver-flex">
							<div class="flex-1 pos-r">
								<div class="pos-a w-h-100">
									<el-table :data="list" class="w-h-100" style="width: 100%" border v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.5)">
										<el-table-column type="index" label="序号" width="55" :show-overflow-tooltip="true" align="center" :index="indexMethod" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="考核表" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="name" typeVal="input" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.name }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="watchmakerName" label="制表人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="headName" label="负责人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="orgName" label="考核部门" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="assesseeName" label="被考核人" align="center">
											<el-table-column min-width="120" :show-overflow-tooltip="true" align="center">
												<template #header>
													<SearchModel typeId="assesseeName" typeVal="select" @searchHandel="searchHandel" :basicsInfo="basicsInfo" />
												</template>
												<template #default="{ row }">
													{{ row.assesseeName }}
												</template>
											</el-table-column>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="dateOfAssessment" label="考核日期" align="center" />
										<el-table-column min-width="80" :show-overflow-tooltip="true" label="总分" align="center">
											<template #default="scope">
												<span v-if="scope.row.score">{{ scope.row.score }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="100" :show-overflow-tooltip="true" label="考核结果" align="center">
											<template #default="scope">
												<span v-if="scope.row.result">{{ scope.row.result }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdTime" label="创建时间" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" prop="createdUserName" label="创建人" align="center" />
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新时间" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedTime">{{ scope.row.updatedTime }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="更新人" align="center">
											<template #default="scope">
												<span v-if="scope.row.updatedUserName">{{ scope.row.updatedUserName }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="120" :show-overflow-tooltip="true" label="考核表备注" align="center">
											<template #default="scope">
												<span v-if="scope.row.remark">{{ scope.row.remark }}</span>
												<span v-else> - </span>
											</template>
										</el-table-column>
										<el-table-column min-width="180" :show-overflow-tooltip="false" label="操作" align="center" fixed="right">
											<el-table-column min-width="180" :show-overflow-tooltip="false" align="center" fixed="right">
												<template #header>
													<el-button @click="searchClick" icon="ele-Search" type="primary" text> 查询 </el-button>
													<el-button @click="resetClick" icon="ele-Refresh" text> 重置 </el-button>
												</template>
												<template #default="scope">
													<div class="operate-s">
														<el-button v-if="$hasPer('quarterlyAssessmentProdSafetyResponsibility2:create')" @click="editClick(scope.row.n_Id)" class="icon-e" icon="ele-EditPen" size="small" text type="primary"> 考核评分 </el-button>
														<el-button v-if="$hasPer('quarterlyAssessmentProdSafetyResponsibility3:edit')" @click="nodeClick(scope.row)" class="icon-e" icon="ele-Edit" size="small" text type="primary"> 编辑 </el-button>
														<el-button v-if="$hasPer('quarterlyAssessmentProdSafetyResponsibility4:delete')" @click="deleteHandle(scope.row.n_Id)" class="icon-e" icon="ele-Delete" size="small" text type="danger"> 删除 </el-button>
													</div>
												</template>
											</el-table-column>
										</el-table-column>
									</el-table>
								</div>
							</div>
							<div style="height: 30px; margin-top: 20px" class="hr-flex-start">
								<el-pagination
									v-model:currentPage="pageNo"
									v-model:page-size="pageSize"
									:total="totalRows"
									:page-sizes="[10, 20, 50, 100]"
									small
									background
									@size-change="handleSizeChange"
									@current-change="handleCurrentChange"
									layout="total, sizes, prev, pager, next, jumper"
									class="w-h-100"
								/>
							</div>
						</div>
					</el-card>
				</div>
			</div>
		</div>
		<!-- 新增and编辑 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="showDialogVisible" :title="saveId ? '编辑' : '新增'" width="50%" @close="cancelUseClick">
			<el-form label-width="110px" ref="ruleFormRef" :model="ruleForm" size="default" :rules="rules">
				<el-divider content-position="left"> 基本信息 </el-divider>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="orgId" label="组织">
							<el-select v-model="ruleForm.orgId" placeholder="组织" style="width: 100%" @change="changeAssessee">
								<el-option v-for="item in options4" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="!saveId">
						<el-form-item prop="assesseeId" label="被考核员工">
							<el-select v-model="ruleForm.assesseeId" placeholder="被考核员工" style="width: 100%" @change="changeAssessee">
								<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20" v-if="!saveId">
						<el-form-item prop="templateFormId" label="考核模板">
							<el-select v-model="ruleForm.templateFormId" placeholder="考核模板" style="width: 100%" @change="changeTemplate">
								<el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item prop="headId" label="负责人">
							<el-select filterable v-model="ruleForm.headId" placeholder="负责人" style="width: 100%" @change="changeHead">
								<el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancelUseClick">取消</el-button>
					<el-button type="primary" @click="controlUseClick(ruleFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<!-- 编辑 -->
		<!-- <el-dialog v-model="showDialogVisible1" title="新增" width="50%" @close="cancelUseClick">
            <el-form label-width="110px" ref="ruleFormRef1" :model="selectData" size="default" :rules="rules1">
                <el-divider content-position="left"> 基本信息 </el-divider>
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
                        <el-form-item prop="orgId" label="组织">
                            <el-select v-model="selectData.orgId" placeholder="组织" style="width: 100%"
                                @change="changeAssessee">
                                <el-option v-for="item in options4" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="cancelUseClick">取消</el-button>
                    <el-button type="primary" @click="controlUseClick1(ruleFormRef1)">确定</el-button>
                </span>
            </template>
        </el-dialog> -->
		<!-- 考核评分 -->
		<el-dialog draggable :close-on-click-modal="false" :close-on-press-escape="false" v-model="dialogVisible" :title="totalScore ? '查看考核评分' : '考核表评分'" width="50%" @close="cancelUseClick1">
			<el-divider content-position="left"> 考核信息 </el-divider>
			<el-form label-width="100px">
				<el-row :gutter="35">
					<el-col v-if="!totalScore" :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="考核结果">
							<el-input v-model="transferVal3" placeholder="请输入考核结果" />
						</el-form-item>
					</el-col>
					<template v-else>
						<el-descriptions :column="2" border class="w-h-100" style="margin: 0 20px;">
							<el-descriptions-item>
								<template #label>
									考核人
								</template>
								{{ descriptionsData.headName }}
							</el-descriptions-item>
							<el-descriptions-item>
								<template #label>
									被考核人
								</template>
								{{ descriptionsData.assesseeName }}
							</el-descriptions-item>
							<el-descriptions-item>
								<template #label>
									总分
								</template>
								{{ descriptionsData.score }}
							</el-descriptions-item>
							<el-descriptions-item>
								<template #label>
									考核结果
								</template>
								{{ descriptionsData.result }}
							</el-descriptions-item>
						</el-descriptions>
					</template>
				</el-row>
			</el-form>
			<el-divider content-position="left"> 考核表 </el-divider>
			<div style="color: red; margin: 10px">注意：扣减分不能超出标准分，否者考核失败</div>
			<el-table :data="descriptionsData.items" border style="width: 100%">
				<el-table-column type="index" align="center" label="序号" min-width="60" />
				<el-table-column prop="projectName" align="center" label="项目名称" min-width="120" :show-overflow-tooltip="true" />
				<el-table-column prop="content" align="center" label="考核内容" min-width="120" :show-overflow-tooltip="true" />
				<el-table-column prop="criterionScores" align="center" label="标准分" min-width="80" :show-overflow-tooltip="true" />
				<el-table-column prop="gradingCriteria" align="center" label="评分标准" min-width="120" :show-overflow-tooltip="true" />
				<el-table-column prop="deductPoints" align="center" label="扣减分" min-width="80" :show-overflow-tooltip="false">
					<template #default="scope">
						<span v-if="totalScore">{{ scope.row.deductPoints }}</span>
						<el-input @blur="(e) => scoreBlur(e)" @focus="(e) => scoreFocus(e)" v-else v-model="scope.row.deductPoints" type="number" />
					</template>
				</el-table-column>
				<el-table-column prop="score" align="center" label="考核得分" min-width="100" v-if="totalScore" :show-overflow-tooltip="true" />
			</el-table>
			<template #footer>
				<span v-if="!descriptionsData.score" class="dialog-footer">
					<el-button @click="cancelUseClick1">取消</el-button>
					<el-button type="primary" @click="controlUseClick1">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import getTableData from '/@/utils/getTableData';
import {
	getSafetyResponsibilityApi,
	deleteSafetyResponsibilityApi,
	updateSafetyResponsibilityApi,
	addSafetyResponsibilityApi,
	getEmployeeAssessmentTemplateApi,
	getEmployeeAssessmentTableApi,
	getEmployeeAssessmentApi,
	getEmployeeAssessmentLeaderApi,
	sysOrgList,
	postExcel2,
} from '/@/api/sms/HazardousChemicalsInterface';
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus';
import SearchModel from '/@/views/sms/component/search-model.vue';

/***** 查询 *****/
let searchObj: any = reactive({});
const transferVal1 = ref();
const transferVal2 = ref();
const transferVal3 = ref();
const searchClick = () => {
	// searchObj.Type = transferVal1.value
	// searchObj.Name = transferVal2.value
	let newObj = Object.keys(searInfo.value);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = searInfo.value[i];
		});
	}
};

const resetClick = () => {
	// transferVal1.value = ''
	// transferVal2.value = ''
	searInfo.value = {};
	let newObj = Object.keys(searchObj);
	if (newObj.length !== 0) {
		newObj.map((i: any) => {
			searchObj[i] = '';
			// console.log(i);
		});
	}
	initInfoFun();
};
/***** 下拉框选择事件 *****/
const options1: any = ref([]); //被考核员工
const options2: any = ref([]); // 考核模板
const options3: any = ref([]); // 负责人
const options4: any = ref([]); //组织
//被考核人
const changeAssessee = async (id: number) => {
	options2.value = [];
	ruleForm.templateFormId = '';

	// 考核表
	const res2 = await getEmployeeAssessmentTemplateApi({ EmpId: id });
	options2.value = res2.data.map((item: any) => {
		return {
			label: item.name,
			value: item.formId,
		};
	});
};

//考核表
const changeTemplate = async (id: number) => {
	options3.value = [];
	ruleForm.headId = '';
	// 考核人
	const res3 = await getEmployeeAssessmentLeaderApi({ TemplateFormId: id, AssesseeId: ruleForm.assesseeId });
	options3.value = res3.data.map((item: any) => {
		return {
			label: item.empName,
			value: item.examinerId,
		};
	});
};

const changeHead = () => {};
/***** 新增 *****/
const showDialogVisible = ref(false);
const ruleForm: any = reactive({
	templateFormId: '', //模板表的id,下拉框，从/SMS/SafetyAssessmentBusinessService/ListTemplate拿
	assesseeId: '', //被考核的员工id,下拉框，从/SMS/SafetyAssessmentBusinessService/ListEmp拿
	headId: '', //负责人id，下拉框，从/SMS/SafetyAssessmentBusinessService/ListHead拿
	orgId: '',
});
const addNodeClick = async () => {
	showDialogVisible.value = true;
};

/***** 编辑 *****/
const saveId = ref(0);

const nodeClick = async (row: any) => {
	saveId.value = row.n_Id;
	console.log(row, 'row');
	options3.value = [];
	// 考核人
	const res3 = await getEmployeeAssessmentLeaderApi({ TemplateFormId: row.templateFormId, AssesseeId: row.assesseeId });
	options3.value = res3.data.map((item: any) => {
		return {
			label: item.empName,
			value: item.examinerId,
		};
	});
	ruleForm.headId = row.headId;
	ruleForm.orgId = String(row.orgId);

	showDialogVisible.value = true;
};
// 考核评分
const scoreBlur = (e) => {
	if (e.target.value === '' || e.target.value < 0) {
		ElMessage.warning('请输入正整数');
		e.target.value = 0;
	}
};

const scoreFocus = (e) => {
	e.target.value = '';
};

const cancelUseClick1 = () => {
	transferVal3.value = '';
	dialogVisible.value = false;
};
const controlUseClick1 = async () => {
	let param = {
		formId: saveId.value,
		result: transferVal3.value,
		itemScores: {},
	};
	const bl = descriptionsData.value.items.some((element: any) => {
		return Number(element.deductPoints) === 0;
	});
	if (bl) {
		ElMessage.warning('考核分数不能为零');
	} else {
		descriptionsData.value.items.forEach((element: any) => {
			console.log(element);
			param.itemScores[element.n_Id] = Number(element.deductPoints);
		});

		if (!transferVal3.value) {
			ElMessage.warning('请输入考核结果');
		} else {
			await postExcel2(param);
			cancelUseClick1();
		}
	}
	console.log(bl);
	// if (!element.deductPoints) {
	//         ElMessage.warning('考核分数不能为零')
	//         return
	//     }else{
	//         // param.itemScores[] =
	//         console.log(descriptionsData.value.items);

	//     }

	//const res = await postExcel2()
};

// const ruleFormRef1 = ref()
// const rules1 = reactive({
//     orgId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
//     headId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
// })
// const controlUseClick1 = async (formEl: FormInstance) => {
//     if (!formEl) return
//     await formEl.validate((valid, fields) => {
//         if (valid) {
//             updateSafetyResponsibilityApi({ ...selectData, businessFormId: saveId.value })
//             setTimeout(() => {
//                 cancelUseClick()
//                 getData()
//             }, 100)
//         } else {
//             console.log('error submit!', fields)
//         }
//     })
// }

/*** 删除 */
const deleteHandle = async (val: String | Number) => {
	ElMessageBox.confirm('请确定删除此条数据', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	})
		.then(async () => {
			let param = { id: val };
			try {
				let res: any = await deleteSafetyResponsibilityApi(param);
				if (res.success) {
					getData();
				}
			} catch (err) {
				return;
			}
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '删除失败',
			});
		});
};

// 详情
const descriptionsData: any = ref();
const totalScore = ref(0);
const dialogVisible = ref(false);
const editClick = async (id: any) => {
	saveId.value = id;
	const res = await getEmployeeAssessmentTableApi({ Id: id });
	descriptionsData.value = res.data;
	totalScore.value = res.data.score;
	dialogVisible.value = true;
};

/***** 新增编辑表单校验和事件 *****/
const ruleFormRef = ref();
const rules = reactive({
	headId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
	orgId: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
});
const cancelUseClick = () => {
	showDialogVisible.value = false;
	saveId.value = 0;
	ruleForm.templateFormId = '';
	ruleForm.assesseeId = '';
	ruleForm.headId = '';
	ruleForm.orgId = '';
	options2.value = [];
	options3.value = [];
};

const controlUseClick = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			if (saveId.value) {
				updateSafetyResponsibilityApi({ ...ruleForm, businessFormId: saveId.value }).then(() => {
					cancelUseClick();
					getData();
				});
			} else {
				addSafetyResponsibilityApi(ruleForm).then(() => {
					cancelUseClick();
					getData();
				});
			}
		} else {
			console.log('error submit!', fields);
		}
	});
};

/*** 初始化数据 */
const basicsInfo: any = ref([]);
const initInfoFun = () => {
	basicsInfo.value = [
		{
			typeId: 'name', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'FormName', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '考核表名字', // placeholder数据
			defaultProp: '', // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
		{
			typeId: 'assesseeName', // 类型(不能为空，且唯一，与组件中typeId值对应) --- 必填
			typeNam: '', // 输入类型(number,text等) --- 选填
			searchVal: 'AssesseeId', // 查询字段 --- 必填
			defaultVal: '', // 字段默认值 --- 选填
			placeholder: '被考核人', // placeholder数据
			defaultProp: options1.value, // 下拉框中使用，除下拉框外其它情况为空 --- 选填
			eventType: '', // 事件类型（如burl/change等） --- 选填
			defaultEvent: '', // 事件名称 --- 选填
		},
	];
};

const searInfo: any = ref();
const searchHandel = (val: any) => {
	searInfo.value = val;
};

const { handleCurrentChange, pageSize, pageNo, handleSizeChange, totalRows, list, indexMethod, loading, getData } = getTableData(getSafetyResponsibilityApi, {}, searchObj);

onMounted(async () => {
	const res1 = await getEmployeeAssessmentApi();
	options1.value = res1.data.map((item: any) => {
		return {
			label: item.empName,
			value: item.id,
		};
	});

	const res4 = await sysOrgList();
	options4.value = res4.data.map((item: any) => {
		return {
			label: item.name,
			value: item.id,
		};
	});

	await initInfoFun();
});
</script>

<style lang="scss">
@import '../style/public.scss';
</style>

<style scoped lang="scss">
#friend-merchant-manage {
	.box-f {
		:deep(.el-form-item__label) {
			padding: 0;
		}
	}

	:deep(.el-card__body) {
		height: 100%;
	}

	:deep(.el-card) {
		border: none !important;
	}

	.upload-demo {
		margin-left: 12px;
		margin-top: 2px;
	}

	ul {
		list-style: none;

		li {
			cursor: pointer;

			&:hover {
				color: red;
			}
		}
	}

	.icon-e {
		:deep(.el-icon) {
			margin-right: 0px !important;
		}
	}
}
</style>
